#include <iostream>
#include <sstream>
#include <vector>
#include <string>
#include <jsoncpp/json/json.h>

std::string serialize()
{
    //1.将需要进行序列化的数据存储在Json::Value对象中
    Json::Value root;
    root["姓名"] = "张三";
    root["年龄"] = 18;
    root["成绩"].append(98);
    root["成绩"].append(88.5);
    root["成绩"].append(78.5);
    
    //2.实例化StreamWriterBuilder工厂类对象
    Json::StreamWriterBuilder swb;

    //3.通过StreamWriterBuilder对象生产StreamWriter对象
    Json::StreamWriter* sw = swb.newStreamWriter();

    //4.使用StreamWriter对象对Json::Value中存储的数据进行序列化
    std::stringstream ss;
    sw->write(root, &ss);
    delete(sw);
    return ss.str();
}

void deserialize(const std::string& s)
{
    Json::CharReaderBuilder crb;

    Json::CharReader* cr = crb.newCharReader();

    Json::Value root;
    std::string err;

    bool ret = cr->parse(s.c_str(), s.c_str() + s.size(), &root, &err);
    delete cr;
    if (!ret)
    {
        std::cout << "deserialize failed. " << err << std::endl;
        return;
    }

    std::cout << root["姓名"].asString() << std::endl;
    std::cout << root["年龄"].asInt() << std::endl;
    std::cout << root["成绩"][0].asFloat() << " " << root["成绩"][1].asFloat() << " " << root["成绩"][2].asFloat() << std::endl;
}


int main()
{
    std::string s = serialize();
    std::cout << s << std::endl;
    deserialize(s);
    return 0;
}